package com.bocom.hairy.crab.web.controller;

import com.bocom.hairy.crab.base.common.SnowFlakeFactory;
import com.bocom.hairy.crab.base.common.enums.BRStyle;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @ClassName com.bocom.hairy.crab.web.controller.SnowFlakeController <br/>
 * @Description: 雪花算法测试        <br/>
 * @Author jiangshikun             <br/>
 * @Date 2025/9/3 下午3:52         <br/>
 * @Version V1.0
 * ----------------------------------------
 * （^-^）心即理，知行合--致良知 （^-^）
 * 邮 箱:duzhuai@live.cn
 * 地 址：北京市海淀区永澄北路2号
 **/
@Tag(name = "雪花算法")
@RestController
@RequestMapping("/snowflake")
@SuppressWarnings("unchecked")
public class SnowFlakeController {

    @Autowired
    private SnowFlakeFactory snowFlakeFactory;

    /**
     * 单个ID
     * @return
     */
    @Operation(summary = "根据ID获取用户")
    @GetMapping("/getCOID")
    public String genSnowFlake() {
        return snowFlakeFactory.nextId(BRStyle.CO);
    }

    /**
     * 批量生成id
     * 开始时间2020-05-27T17:01:34.176
     * 结束时间2020-05-27T17:01:34.463
     * 200000
     * 结论：300ms生成 20w个无重复的id
     * @return
     */
    @Operation(summary = "批量生成id")
    @GetMapping("/batchCreateID")
    public Set batchCreateID() throws ExecutionException, InterruptedException {
        int count = 20;

        System.out.println("开始生成id......");
        ExecutorService executor = Executors.newCachedThreadPool();

        List countList = new ArrayList();
        //测试生成20w个id
        for (int i = 0; i < count; i++) {
            countList.add(i);
        }

        //使用set测试是否有重复，结果没有任何重复
        Set list = Collections.synchronizedSet(new HashSet<>());
        System.out.println("开始时间" + LocalDateTime.now());
        countList.parallelStream().forEach((i) -> {
            Future<String> futureTask = executor.submit(() -> {
                return snowFlakeFactory.nextId(BRStyle.CO);
            });
            String id = null;
            try {
                id = futureTask.get();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            list.add(id);
        });
        System.out.println("结束时间" + LocalDateTime.now());
        System.out.println(list.size());
        return list;
    }
}
